package cn.gbase.jiangsu.data.transfer.service;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.nutz.dao.Cnd;
import org.nutz.filepool.FilePool;
import org.nutz.filepool.NutFilePool;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Files;
import org.nutz.lang.Lang;
import org.nutz.mvc.upload.FieldMeta;
import org.nutz.service.IdEntityService;

import cn.gbase.jiangsu.data.transfer.action.SupplierProductAction;
import cn.gbase.jiangsu.data.transfer.bean.TFile;

@IocBean(fields = { "dao" })
public class TFileService extends IdEntityService<TFile> {

	@Inject("java:$config.get('picUpload')")
	private String path;

	@Inject
	private final FilePool wjscFilePool = new NutFilePool("D:/geyun/abc");

	public void saveOrUpdate(TFile file, File uploadFile, FieldMeta meta) {
		try {
			//String fileUrl = "/abc/" + meta.getFileLocalName() + ".png";
			//String copyFile = "D:/geyun/geyun/WebContent/abc/" + meta.getFileLocalName() + ".png";

			String urlNew = path;

			UUID uuid = UUID.randomUUID();

			String fileHouZhui = meta.getFileExtension();

			String copyFile = new SupplierProductAction().findServerPath() + path + uuid.toString() + fileHouZhui;

			file.setWjUrl(urlNew + uuid.toString() + fileHouZhui);
			if (file.getWjId() != null) {
				file.setWjbm(uuid.toString() + fileHouZhui);
				dao().updateIgnoreNull(file);
			} else {
				file.setWjbm(uuid.toString() + fileHouZhui);
				dao().insert(file);
			}
			File poolFile = null;
			if (wjscFilePool.hasFile(file.getWjId(), "")) {
				poolFile = wjscFilePool.getFile(file.getWjId(), "");
			} else {
				poolFile = wjscFilePool.returnFile(file.getWjId(), "");
			}
			Files.copyFile(uploadFile, poolFile);

			//将文件复制到指定目录下
			File fileNew = new File(copyFile);
			Files.copy(uploadFile, fileNew);
		} catch (IOException e) {
			throw Lang.wrapThrow(e);
		}
	}

	public File getFile(Integer wjId) {
		return wjscFilePool.getFile(wjId, "");
	}

	public void deleteFile(Integer wjId) {
		wjscFilePool.removeFile(wjId, "");
	}

	public List<TFile> queryAllFile(String ywid, HttpServletRequest req) {
		List<TFile> fileList = this.dao().query(TFile.class, Cnd.where("ywid", "=", ywid));
		/*File poolFile = null;
		for (TFile tFile : fileList) {
			if (wjscFilePool.hasFile(tFile.getWjId(), "")) {
				poolFile = wjscFilePool.getFile(tFile.getWjId(), "");
			} else {
				poolFile = wjscFilePool.returnFile(tFile.getWjId(), "");
			}
			//poolFile = wjscFilePool.getFile(tFile.getWjId(), "");
			String fileUrl = "/abc/" + poolFile.getName() + ".png";
			String copyFile = "D:/geyun/geyun/WebContent/abc/" + poolFile.getName() + ".png";
			File file = new File(copyFile);
			Files.copy(poolFile, file);
			tFile.setWjUrl(fileUrl);
		}*/
		return fileList;
	}
}
